package logic

import (
	"context"
	"fmt"
	"house/models/cache"
	"house/models/mysql"

	"house/userrpc/internal/svc"
	"house/userrpc/userrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type FindPasswordLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewFindPasswordLogic(ctx context.Context, svcCtx *svc.ServiceContext) *FindPasswordLogic {
	return &FindPasswordLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *FindPasswordLogic) FindPassword(in *userrpc.FindPasswordRequest) (*userrpc.FindPasswordResponse, error) {
	// todo: add your logic here and delete this line
	result, _ := cache.Rdb.Get(l.ctx, "sendSms"+in.Mobile).Result()
	if result != in.SmsCode {
		return nil, fmt.Errorf("当前短信验证码输入错误")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)

	if in.Password != in.Newpassword {
		return nil, fmt.Errorf("两次密码输入不一致，请重新输入")
	}
	if user.Password == in.Password {
		return nil, fmt.Errorf("新密码与旧密码一致，请重新输入")
	}
	user.Password = in.Password
	return &userrpc.FindPasswordResponse{
		UserId: int64(user.ID),
	}, nil
}
